package com.company.loganalyzer.controller;

import com.company.loganalyzer.dto.ToolInput;
import com.company.loganalyzer.dto.ToolResult;
import com.company.loganalyzer.dto.TraceAnalysisRequest;
import com.company.loganalyzer.dto.TraceAnalysisResponse;
import com.company.loganalyzer.tools.impl.TraceAnalysisTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 日志分析工具控制器
 * 
 * 提供原有的工具API接口，保持与Python版本的兼容性
 */
@RestController
@RequestMapping("/api/v1/log-analysis")
public class LogAnalysisController {
    
    @Autowired
    private TraceAnalysisTool traceAnalysisTool;
    
    /**
     * 获取可用工具列表
     */
    @GetMapping("/tools")
    public Map<String, Object> getAvailableTools() {
        Map<String, Object> response = new HashMap<>();
        response.put("tools", Arrays.asList(
            Map.of("name", "search_logs", "description", "搜索和过滤日志"),
            Map.of("name", "analyze_errors", "description", "分析错误和异常"),
            Map.of("name", "get_log_statistics", "description", "统计分析"),
            Map.of("name", "trace_error_context", "description", "追踪分析"),
            Map.of("name", "trace_analysis", "description", "基于traceId进行智能链路分析")
        ));
        response.put("timestamp", LocalDateTime.now());
        return response;
    }
    
    /**
     * 日志搜索工具
     */
    @PostMapping("/tools/search_logs")
    public ToolResult searchLogs(@RequestBody ToolInput input) {
        Map<String, Object> result = new HashMap<>();
        result.put("message", "日志搜索功能已执行");
        result.put("query", input.getQuery());
        result.put("timeRange", input.getTimeRange());
        result.put("level", input.getLevel());
        result.put("limit", input.getLimit());
        result.put("note", "这是简化版本的模拟结果");
        
        return ToolResult.success("search_logs", result);
    }
    
    /**
     * 错误分析工具
     */
    @PostMapping("/tools/analyze_errors")
    public ToolResult analyzeErrors(@RequestBody ToolInput input) {
        Map<String, Object> result = new HashMap<>();
        result.put("message", "错误分析功能已执行");
        result.put("timeRange", input.getTimeRange());
        result.put("serviceName", input.getServiceName());
        result.put("note", "这是简化版本的模拟结果");
        
        return ToolResult.success("analyze_errors", result);
    }
    
    /**
     * 统计分析工具
     */
    @PostMapping("/tools/get_log_statistics")
    public ToolResult getLogStatistics(@RequestBody ToolInput input) {
        Map<String, Object> result = new HashMap<>();
        result.put("message", "统计分析功能已执行");
        result.put("timeRange", input.getTimeRange());
        result.put("groupBy", input.getGroupBy());
        result.put("note", "这是简化版本的模拟结果");
        
        return ToolResult.success("get_log_statistics", result);
    }
    
    /**
     * 追踪分析工具
     */
    @PostMapping("/tools/trace_error_context")
    public ToolResult traceErrorContext(@RequestBody ToolInput input) {
        Map<String, Object> result = new HashMap<>();
        result.put("message", "追踪分析功能已执行");
        result.put("traceId", input.getTraceId());
        result.put("timeRange", input.getTimeRange());
        result.put("note", "这是简化版本的模拟结果");
        
        return ToolResult.success("trace_error_context", result);
    }
    
    /**
     * TraceId智能分析工具
     * 基于SkyWalking链路追踪，深度分析指定traceId的调用链路
     */
    @PostMapping("/tools/trace_analysis")
    public ToolResult traceAnalysis(@RequestBody ToolInput input) {
        return traceAnalysisTool.execute(input);
    }
    
    /**
     * TraceId智能分析 - 专用API接口
     * 提供更详细的参数控制和响应格式
     */
    @PostMapping("/trace-analysis")
    public TraceAnalysisResponse analyzeTrace(@RequestBody TraceAnalysisRequest request) {
        // 转换为ToolInput格式
        ToolInput toolInput = new ToolInput();
        toolInput.setTraceId(request.getTraceId());
        toolInput.setTimeRange(request.getTimeRange());
        toolInput.setServiceName(request.getServiceName());
        toolInput.setLimit(request.getMaxLogs());
        
        // 执行分析
        ToolResult result = traceAnalysisTool.execute(toolInput);
        
        // 返回专用格式的响应
        if ("success".equals(result.getStatus())) {
            return (TraceAnalysisResponse) result.getData();
        } else {
            return TraceAnalysisResponse.failure(request.getTraceId(), result.getMessage());
        }
    }
    
    /**
     * TraceId分析 - 快速接口 (GET方式，方便测试)
     */
    @GetMapping("/trace-analysis/{traceId}")
    public TraceAnalysisResponse analyzeTraceQuick(@PathVariable String traceId,
                                                   @RequestParam(defaultValue = "last_24h") String timeRange) {
        TraceAnalysisRequest request = new TraceAnalysisRequest(traceId);
        request.setTimeRange(timeRange);
        return analyzeTrace(request);
    }
}